package com.chukun.reactor.master;


import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author chukun@meituan.com
 * @version 1.0.0
 * @description 主线程池分发
 * @create 2022/1/25 21:14
 **/
public class MultiplyReactor {

    private static final int POOL_SIZE = Runtime.getRuntime().availableProcessors();
    // Reactor（Selector） 线程池，其中一个线程被 mainReactor 使用，剩余线程都被 subReactor 使用
    private static Executor masterReactorExecutor = Executors.newFixedThreadPool(POOL_SIZE);
    // 主 Reactor,接收连接，把SocketChannel注册到从 Reactor上
    private Reactor masterReactor;

    private int port;

    public MultiplyReactor(int port) {
        try {
            this.port = port;
            masterReactor = new Reactor();
        } catch (Exception e) {

        }
    }

    /**
     * 启动主从 Reactor，初始化并注册 Acceptor 到主 Reactor
     */
    public void start() throws IOException {
        new Acceptor(masterReactor.getSelector(), port); // 将 ServerSocketChannel 注册到 mainReactor
        masterReactorExecutor.execute(masterReactor); //使用线程池来处理main Reactor的连接请求
    }
}
